const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { usersDB } = require('./database');

class AuthService {
  async register({ username, email, password }) {
    const existingUser = (await usersDB.read()).find(u => u.email === email);
    if (existingUser) throw new Error('邮箱已被注册');

    const hashedPassword = await bcrypt.hash(password, 10);
    return usersDB.insert({
      username,
      email,
      password: hashedPassword,
      verified: false,
      createdAt: new Date().toISOString()
    });
  }

  async login({ identifier, password }) {
    const user = (await usersDB.read()).find(u => 
      u.email === identifier || u.username === identifier
    );
    
    if (!user || !(await bcrypt.compare(password, user.password))) {
      throw new Error('无效的登录凭证');
    }
    
    return jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '2h' });
  }
}

module.exports = new AuthService();
